/**
 * Created by chen on 2018/12/22.
 */
// 省、市下拉列表查询(需在object init之后调用)
function searchAreaList(areaCode, objectId) {
    var def = $.Deferred();
    var areaInfo = {
        areaList: []
    }
//   setTimeout(function() {
//     if (areaCode === '990010000000000000') {
//         // 返回省平台
//         areaInfo.areaList.push({areaName:'河北平台', areaCode:'020010000000000000'})
//         areaInfo.areaList.push({areaName:'北京平台', areaCode:'030010000000000000'})
//     } else if (areaCode === '020010000000000000') {
//       areaInfo.areaList.push({areaName:'石家庄平台', areaCode:'050010000000000000'})
//       areaInfo.areaList.push({areaName:'沧州平台', areaCode:'060010000000000000'})
//     } else {
//         // 返回北京  需要确定北京这块这种直辖市是怎么返回的
//       areaInfo.areaList.push({areaName:'北京平台', areaCode:'070010000000000000'})
//     }
//     def.resolve(areaInfo);
//   }, 100);
//   return def;
    var xmlStr = document.getElementById(objectId).ocxVideoResQuery(areaCode+'')
    $(xmlStr).find("Item").each(function() {
        var item = $(this);
        var name = item.attr("Name");//读取节点属性
        var code = item.attr("Code");//读取节点属性
        areaInfo.areaList.push({areaName:name, areaCode:code})
    });
    def.resolve(areaInfo);
    return def;
}


// 营业厅列表查询(根据市返回的是各个场景的列表，需要再筛一层)
function searchHallList(areaCode, objectId) {
    var def = $.Deferred();
    var hallInfo = {
        hallList: []
    }
//   setTimeout(function() {
//     if (areaCode === '050010000000000000') {
//       // 营业厅 石家庄
//       hallInfo.hallList.push({hallName:'桥西区1号营业厅', hallValue:'020010000000000000'})
//       hallInfo.hallList.push({hallName:'桥西区2号营业厅', hallValue:'030010000000000000'})
//     } else if (areaCode === '060010000000000000') {// 沧州
//       hallInfo.hallList.push({hallName:'城区1号营业厅', hallValue:'06010000000000000'})
//     } else {
//       // 返回北京
//       hallInfo.hallList.push({hallName:'西直门营业厅', hallValue:'06030000000000000'})
//     }
//     def.resolve(hallInfo);
//   }, 100);
//   return def;
    var xmlStr = document.getElementById(objectId).ocxVideoResQuery(areaCode+'')
    var xmlStrForHall;
    $(xmlStr).find("Item").each(function() {
        var item = $(this);
        var name = item.attr("Name");//读取节点属性
        var code = item.attr("Code");//读取节点属性
        // 目前假设会有返回字段sceneTypeCode且市下层返回name有营业厅
        //if (name == '营业厅')

        if(name.search("营业厅") != -1) {
            // 包含营业厅则查下一层查到具体营业厅
            xmlStrForHall = document.getElementById(objectId).ocxVideoResQuery(code+'')
        }
        //areaInfo.areaList.push({areaName:name, areaCode:code})
    });
    $(xmlStrForHall).find("Item").each(function() {
        var item = $(this);
        var name = item.attr("Name");//读取节点属性
        var code = item.attr("Code");//读取节点属性
        // 目前假设会有返回字段sceneTypeCode且市下层返回name有营业厅
        hallInfo.hallList.push({hallName:name, hallValue:code})
    });
    def.resolve(hallInfo);
    return def;
}

// 摄像头列表获取
function searchVideoList(areaCode, objectId) {
    var def = $.Deferred();
    var videoInfo = {
        videoList: []
    }
    // setTimeout(function() {
    //     if (areaCode === '020010000000000000') {
    //         // 营业厅 石家庄
    //         videoInfo.videoList.push({videoName:'中心营业厅-业务柜台1号', videoCode:'040110000003040010', decoderTag:150})
    //         videoInfo.videoList.push({videoName:'中心营业厅-业务柜台2号', videoCode:'040110000003040011', decoderTag:150})
    //         videoInfo.videoList.push({videoName:'中心营业厅-业务柜台3号', videoCode:'040110000003040012', decoderTag:150})
    //         videoInfo.videoList.push({videoName:'中心营业厅-业务柜台4号', videoCode:'040110000003040012', decoderTag:150})
    //         videoInfo.videoList.push({videoName:'中心营业厅-业务柜台5号', videoCode:'040110000003040012', decoderTag:150})
    //         videoInfo.videoList.push({videoName:'中心营业厅-业务柜台6号', videoCode:'040110000003040012', decoderTag:150})
    //     } else if (areaCode === '030010000000000000') {// 沧州
    //         videoInfo.videoList.push({videoName:'桥西区2号营业厅-大厅', videoCode:'06010000000000000', decoderTag:150})
    //     } else if (areaCode === '06010000000000000') {
    //         // 返回北京
    //         videoInfo.videoList.push({videoName:'城区1号营业厅-大厅', videoCode:'06030000000000000', decoderTag:150.0})
    //     } else {
    //         videoInfo.videoList.push({videoName:'西直门营业厅-柜台', videoCode:'06030000000000000', decoderTag:150.0})
    //     }
    //     def.resolve(videoInfo);
    // }, 100);
    // return def;
    var xmlStr = document.getElementById(objectId).ocxVideoResQuery(areaCode)
    $(xmlStr).find("Item").each(function() {
        var item = $(this);
        var name = item.attr("Name");//读取节点属性
        var code = item.attr("Code");//读取节点属性
        var decoder = item.attr("DecoderTag");//读取节点属性
        videoInfo.videoList.push({videoName:name, videoCode:code, decoderTag:decoder})
    });
    def.resolve(videoInfo);
    return def;

}

// 以下来自视频demo
// 调用ocx接口方法要传递的参数变量
var localIp, sipIp, sipPort, httpIp, httpPort, userCode, userName, pswd;

// 设置调用ocx接口方法要传递的参数变量值
function setConfigInfo(infoArray) {
    this.sipIp = infoArray[2];
    this.sipPort = infoArray[3];
    this.httpIp = infoArray[0];
    this.httpPort = infoArray[1];
    this.userCode = infoArray[4];
    this.userName = infoArray[5];
    this.pswd = infoArray[6];
    this.localIp = infoArray[7];
}

// 页面加载时调用ocxHtmlLoad方法
// if (window.attachEvent) {
//     window.attachEvent("onload", ocxHtmlLoad);
// } else if (window.addEventListener) {
//     window.addEventListener("load", ocxHtmlLoad, false);
// }

// 页面改变大小时调用ocxHtmlResize方法
// if (window.attachEvent) {
//     window.attachEvent("onresize", ocxHtmlResize);
// } else if (window.addEventListener) {
//     window.addEventListener("resize", ocxHtmlResize, false);
// }
// if (window.attachEvent) {
//     window.attachEvent("onbeforeunload", uninit); // 页面在反加载之前调用uninit方法
// } else if (window.addEventListener) {
//     window.attachEvent("onbeforeunload", uninit);
// }

var localIPArray;
var hasLocalIp = false
var videoMainWndIndex,historyMainWndIndex;
var ipList;
function ocxHtmlLoad(objectId) {
    try {
        var result;
        //httpIp： httpIP地址
        //httpPort：httpIP端口
        //sipIp：   sipIP地址
        //sipPort： sip端口
        //userCode： 用户编码
        //userName： 用户名称

        //pswd：用户密码（Md5秘文）
        //localIp：本地ip地址
        var infoArray = ["10.1.150.251", 7506, "10.1.150.251", 7501, "990010000004000001", "role_ywy", "fca812f055d5fdcd3a355b63ceaad991", ""];
        if (!hasLocalIp) {
            setConfigInfo(infoArray);
        }
        //         result = document.getElementById(objectId).ocxInitLocalAddr(localIp, 0, localIp, 0);
        //     if (result == 0) {

        //     } else {
        //         alert("视频播放控件初始化错误！");
        //         return;
        //     }
        // } catch (err) {
        // }
        // try {
        //请求Flex执行OCX端发起执行OCX登录
        loginServer(localIp, sipIp, sipPort, httpIp, httpPort, userCode, userName, pswd,objectId);
        var isResult = document.getElementById(objectId).ocxOcxIsInit();
        if (isResult) {
            //$("#"+objectId).focus()
            //创建窗口(实时视频)
            //videoMainWndIndex = document.getElementById(objectId).ocxCreateWindow(1, 1, 1);
            // 不展示标题栏
            //document.getElementById(objectId).ocxSetWndTitleBar(0);
            //创建窗口(历史视频)
            //historyMainWndIndex = document.getElementById('playerMap').ocxCreateWindow(16, 1, 0);

            //return videoMainWndIndex;
        } else {
            alert("ocx初始化未成功！");
        }
    } catch (err) {
        txt = "视频播放控件初始化错误，无法自动下载安装控件.\n\n如果本站点不是可信任站点，请先配置为可信任站点，再重新登陆系统.";
        alert(txt);
        return;
    }
}
// 创建主窗口
function createWindow(objectId) {
    //创建窗口(实时视频)
    videoMainWndIndex = document.getElementById(objectId).ocxCreateWindow(1, 1, 1);
    // 不展示标题栏
    document.getElementById(objectId).ocxSetWndTitleBar(0);

    return videoMainWndIndex;
}
function ocxHtmlResize() {
    iBody_onresizestart(this);
}

// 创建窗口
function oCreateWindow(sMaxWinNums, sDefaultWinNums) {
    playerMap.ocxCreateWindow(sMaxWinNums, sDefaultWinNums);
}

// 获取报警监听ip
// function ocxLoginServer(args) {
//     isReTimer = args[0]
//     var infoArray = this.parent.document.getElementById('index').getOCX(localIPArray);
//     setConfigInfo(infoArray);
//     // ocx登录
//     loginServer(localIp, sipIp, sipPort, httpIp, httpPort, userCode, userName, pswd);
//     iBody_onresizestart(this);
// }

// 新的登录视频服务器 初始化方式
function loginServer(localIps, sipIp, sipPort, httpIp, httpPort, userCode,
                     userName, pswd, objectId) {
    //alert("localIp + sipIp + sipPort + httpIp + httpPort + userCode + userName + pswd=" +localIp + sipIp + sipPort + httpIp + httpPort + userCode + userName + pswd);
    try {
        //初始化本地信息
        if (!hasLocalIp) {
            var ipStr = document.getElementById(objectId).ocxGetLocalIPList();
            ipList=ipStr.split(";"); //字符分割
            for (i=0;i<ipList.length ;i++ )
            {
                localIp = ipList[i];
                var result = document.getElementById(objectId).ocxInitLocalAddr(localIp, 0, localIp, 0);
                var loginResult = document.getElementById(objectId).ocxLogin(httpIp, httpPort, userName, pswd, 1, 0);
                if (loginResult == 0) {
                    hasLocalIp = true
                    break;
                    //setTimeout(openVideo(videoMainWndIndex, p_cameraCode, pNotes, objectId),1000)
                }
                var last = ipList.length-1
                if (i == last) {
                    //获取错误信息
                    GetOCXInitErrorString(loginResult);
                }
            }
        } else {
            var result = document.getElementById(objectId).ocxInitLocalAddr(localIp, 0, localIp, 0);
            var loginResult = document.getElementById(objectId).ocxLogin(httpIp, httpPort, userName, pswd, 1, 0);
            if (loginResult == 0) {
                //setTimeout(openVideo(videoMainWndIndex, p_cameraCode, pNotes, objectId),1000)
            } else {
                //获取错误信息
                GetOCXInitErrorString(loginResult);
            }
        }

    } catch (err) {
        txt = "ocx控件登录错误，点击“确定”继续。\n\n";
        nalert(txt);
        return;
    }
    //parent.window.closeLoading();

}
function openVideo(videoMainWndIndexNew, p_cameraCode, pNotes, objectId) {
    //startVideo([videoMainWndIndex, 0, 150.0, "040210000003020001", "海康球机1"]);
    startVideo([videoMainWndIndexNew, 0, 150.0, p_cameraCode, pNotes], objectId);
}
// 获取错误信息
function GetOCXInitErrorString(error) {
    var str = "未知错误";
    switch (error) {
        case 180: str = "密码错误"; break;
        case 168: str = "权限不足"; break;
        case 169: str = "用户不存在"; break;
        //case 171:str = "负荷满";break;
        case 171: str = "连接超时"; break;
    }
    if (error != 0) {
        alert("控件登录失败:" + str);
    }
}
// 反初始化
function uninit(videoMainWndIndexNew, objectId) {
    // 控件窗口销毁
    try {
        var r2 = document.getElementById(objectId).ocxDestroyWindow(videoMainWndIndexNew);
    } catch (err) {
        return;
    }
    try {
        var r3 = document.getElementById(objectId).ocxLogout();
    } catch (err) {
        return;
    }
    try {
        var r4 = document.getElementById(objectId).ocxUnInit();
    } catch (err) {
        return;
    }
}
// 设置窗口显示个数
function pchenge(args, objectId) {
    //sMainWndIndex,sWndNums
    document.getElementById(objectId).ocxSetWndNums(args[0], args[1]);
}
// 调阅视频
//sMainWndIndex 主窗口号
//sSubWndNo 子窗口号
//sDecoderTag 解码标签
//p_cameraCode 摄像头编码
//pNotes 摄像头名称
function startVideo(args, objectId) {
    //sMainWndIndex,sSubWndNo,sDecoderTag,p_cameraCode,pNotes
    //alert("sMainWndIndex="+args[0]+"//sSubWndNo="+ args[1]+"//sDecoderTag="+args[2]+"//p_cameraCode="+args[3]+"//pNotes="+args[4]);
    try {
        var result = document.getElementById(objectId).ocxVideoStart(
            args[0], args[1], args[2], args[3], args[4]);
    } catch (err) {
        return;
    }
}
// 停止调阅视频播放
function stopVideo(args, objectId) {
    //sMainWndIndex,sSubWndNo
    document.getElementById(objectId).ocxVideoStop(args[0], args[1]);

}
// 停止调阅所有视频播放
function stopAllVideo(sMainWndIndex, objectId) {
    //sMainWndIndex,sSubWndNo
    var result = document.getElementById(objectId).ocxVideoStopAll(
        sMainWndIndex);
    //alert(result);
}

// 重新调整窗口大小
function iBody_onresizestart(_height, _width, objectId) {
    //var _height = de.document.body.offsetHeight;
    //var _width = de.document.body.offsetWidth;
    document.getElementById(objectId).ocxSetWindowSize(0, _height,
        _width);
}
// 获取当前聚焦窗口
function ocxGetActiveWndNo(v_sMainWndIndex, objectId) {
    var index = document.getElementById(objectId).ocxGetActiveWndNo(
        v_sMainWndIndex);
    return index;
}
// 获取当前是否在录像
function ocxExistRecording(objectId) {
    var result = document.getElementById(objectId).ocxExistRecording();
    return result;
}
function showXXX(sMainWndIndex, sSubWndNo, pCode) {
    // this.parent.document.getElementById('index').getActiveWndCode(sMainWndIndex, sSubWndNo, pCode);
}

function getRPath() {
    var pathName = window.location.pathname;
    var webName = pathName == '' ? '' : pathName.substring(0, pathName
        .lastIndexOf('/'));
    var rootPath = webName == '' ? window.location.protocol + '//'
    + window.location.host + webName : window.location.protocol
    + '//' + window.location.host + webName + '/';
    var path = rootPath + "assets/OcxPlayer/GridControl.zip";
    window.location.href = path;

}





// var str = '<?xml version="1.0" encoding="UTF-8"?>'
// str +='<HTTP_XML EventType="Response_Resource" >'
// str +='<SubList Code="990010000000000000" RealNum="32" SubNum="32"'
// str +='FromIndex="1" ToIndex="32" >'
// str +='<Item Code="010010000000000000" Name="冀北平台" Status="1" DecoderTag="0"'
// str +='Longitude="0" Latitude="0" SubNum="8" />'
// str +='<Item Code="020010000000000000" Name="北京平台" Status="1" DecoderTag="0"'
// str +='Longitude="0" Latitude="0" SubNum="19" />'
// str +='</SubList>'
// str +='</HTTP_XML>'
// var testInfo = {
//     testList: []
//   }
// $(str).find("Item").each(function() {
//   var item = $(this);


//     var name = item.attr("Name");//读取节点属性
//     var code = item.attr("Code");//读取节点属性
//     console.log(code+'!!!')
//     testInfo.testList.push({areaName:name,areaCode:code})
//     console.log(testInfo)
//  });

